<template>
    <el-dialog
      v-model="dialogVisible"
      title="修改密码"
      width="400px"
      @close="handleClose"
      draggable
    >
      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="formRef"
        label-position="top"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            type="password"
            v-model="passwordForm.oldPassword"
            show-password
            placeholder="请输入当前使用的密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            type="password"
            v-model="passwordForm.newPassword"
            show-password
            placeholder="请输入8-20位的新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            type="password"
            v-model="passwordForm.confirmPassword"
            show-password
            placeholder="请再次输入新密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="isLoading" @click="submitForm">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref, reactive, watch } from 'vue';
  import { useUserStore } from '@/stores/user.js';
  import { ElMessage ,ElMessageBox} from 'element-plus';
  
  const props = defineProps({
    modelValue: Boolean,
  });
  const emit = defineEmits(['update:modelValue']);
  
  const userStore = useUserStore();
  const formRef = ref(null);
  const dialogVisible = ref(props.modelValue);
  const isLoading = ref(false);
  
  // 监听 props 的变化来更新 dialogVisible
  watch(() => props.modelValue, (val) => {
    dialogVisible.value = val;
  });
  
  // 监听 dialogVisible 的变化来更新 props
  watch(dialogVisible, (val) => {
    emit('update:modelValue', val);
  });
  
  const passwordForm = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
  });
  
  // 自定义校验规则：确认密码
  const validateConfirmPassword = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请再次输入新密码'));
    } else if (value !== passwordForm.newPassword) {
      callback(new Error("两次输入的新密码不一致!"));
    } else {
      callback();
    }
  };
  
  const passwordRules = {
    oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 8, max: 20, message: '密码长度需在8-20位', trigger: 'blur' },
    ],
    confirmPassword: [
      { required: true, message: '请确认新密码', trigger: 'blur' },
      { validator: validateConfirmPassword, trigger: 'blur' },
    ],
  };
  
  const submitForm = async () => {
    if (!formRef.value) return;
    await formRef.value.validate((valid) => {
      if (valid) {
        isLoading.value = true;
        userStore.changePassword(
          passwordForm.oldPassword,
          passwordForm.newPassword,
          () => { // 成功回调
            isLoading.value = false;
            dialogVisible.value = false; // 关闭弹窗
            ElMessage.success('密码修改成功，请重新登录！');
            // 修改密码后通常需要用户重新登录
            setTimeout(() => {
              userStore.logout();
            }, 1500);
          },
          () => { // 失败回调
            isLoading.value = false;
          }
        );
      }
    });
  };
  
  // 关闭弹窗时重置表单
  const handleClose = () => {
    if (formRef.value) {
      formRef.value.resetFields();
    }
  };
  </script>